# BSD3.0
# cili@163.com


from http.server import SimpleHTTPRequestHandler
from urllib.parse import unquote_plus
import tokenizer
import indexer
import ranker

class SearchHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        self.connection.settimeout(2)
        kws = []
        if self.path.startswith('/search?'):
            keyword = self.path.split('=')[-1]
            keyword = unquote_plus(keyword)
            keyword= keyword.replace(' ','')
            kws = [] if len(keyword)<=1 else tokenizer.cut(keyword)

        message = self.gen_page(kws)
        self.send_response(200)
        self.send_header('Content-type', 'text/html;charset=utf-8')
        self.end_headers()
        self.wfile.write(message)

    def gen_page(self,kws):
        header = ['<html><body><h1>简易搜索</h1><form action="/search" method="get"><input type="text" name="kw" ><input type="submit" value="搜索" ></form>']
        footer = ['</body></html>']
        body = []
        for keyword in kws:
            result = indexer.search_keyword(keyword)
            result = ranker.sort_pages(result)
            body = body + [f'<h3>关于 {keyword} 为您找到以下结果：</h3>']+[f'<p>出现{n}次:<a href={url}> {title}</a></p><br>' for n,url,title in result]
        return ''.join(header + body + footer).encode('utf-8')